/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.ap.web;

import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.google.gson.Gson;
import com.jeeplus.modules.ap.entity.EarningsDetail;

import com.jeeplus.modules.ap.entity.Yue;
import com.jeeplus.modules.ap.service.YueService;
import com.jeeplus.modules.ap.util.Export;

import com.jeeplus.modules.infor.entity.Department;
import com.jeeplus.modules.infor.entity.Staff;
import com.jeeplus.modules.infor.service.DepartmentService;
import com.jeeplus.modules.infor.service.ProjectService;
import com.jeeplus.modules.infor.service.StaffService;
import com.jeeplus.modules.sys.utils.UserUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.ap.entity.Income;
import com.jeeplus.modules.ap.service.IncomeService;

/**
 * 收入Controller
 * @author slD
 * @version 2017-11-30
 */
@Controller
@RequestMapping(value = "${adminPath}/ap/income")
public class IncomeController extends BaseController {

	@Autowired
	private IncomeService incomeService;
	@Autowired
	private ProjectService projectService;
	@Autowired
	private StaffService staffService;
	@Autowired
	private YueService yueService;
	@Autowired
	private DepartmentService departmentService;
	@ModelAttribute
	public Income get(@RequestParam(required=false) String id) {
		Income entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = incomeService.get(id);
		}
		if (entity == null){
			entity = new Income();
		}
		return entity;
	}
	
	/**
	 * 收入列表页面
	 */
	@RequiresPermissions("ap:income:list")
	@RequestMapping(value = {"list", ""})
	public String list() {
		return "modules/ap/incomeList";
	}
	/**
	 * 收入列表页面
	 */
	@RequiresPermissions("ap:income:list")
	@RequestMapping(value = {"list1"})
	public String list1() {
		return "modules/ap/2/incomeList";
	}
	
		/**
	 * 收入列表数据
	 */
	@ResponseBody
	@RequiresPermissions("ap:income:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(Income income, HttpServletRequest request, HttpServletResponse response, Model model) {
		String pro= UserUtils.getUseroffice();
		if(!pro.equals("总部")){
			income.setProjectName(projectService.findUniqueByProperty("name",pro));}
		Page<Income> page = incomeService.findPage(new Page<Income>(request, response), income);
		return getBootstrapData(page);
	}

	/**
	 * 确认提交
	 */
	@ResponseBody
	@RequestMapping(value = "qr")
	public AjaxJson qr(Income income, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		income.setDocumentStatus("已确认待审批");
		incomeService.save(income);
		j.setMsg("确认成功");
		return j;
	}
	/**
	 * 收入列表数据
	 */
	@ResponseBody
	@RequiresPermissions("ap:income:list")
	@RequestMapping(value = "data1")
	public Map<String, Object> data1(Income income, HttpServletRequest request, HttpServletResponse response, Model model) {
		String pro= UserUtils.getUseroffice();
		if(!pro.equals("总部")){
			income.setProjectName(projectService.findUniqueByProperty("name",pro));}
			income.setDocumentStatus("总经理已审批");
		Page<Income> page = incomeService.findPage(new Page<Income>(request, response), income);
		return getBootstrapData(page);
	}

	@ResponseBody
	@RequestMapping(value="cx")
	public String cx(String min,String max,String pro,String dx,String gs){
		Income i=new Income();
		if(pro!=null &&!pro.equals("")&&!pro.equals("undefined")){
			i.setProjectName(projectService.get(pro));
		}else{
			if(!UserUtils.getUseroffice().equals("总部")){
				i.setProjectName(projectService.findUniqueByProperty("name",UserUtils.getUseroffice()));
			}
		}
		i.setMinDate(min);
		i.setMax(max);
		i.setCostObject(dx);
		i.setCostAffiliation(gs);
		i.setDocumentStatus("财务已审批");
		List<Income> list=incomeService.findList(i);
		double hz=0.0;
		String ids="";
		for(Income in:list){
		hz+=in.getMoney();
		ids+=in.getId()+",";
		}
		i.setMoney(hz);
		i.setMax(ids);
		list.add(i);
		Gson g=new Gson();
		return g.toJson(list).toString();
	}

	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequestMapping(value = "daochu")
	public void daochu0(HttpServletResponse response,String ids) {
		//获取数据
		String[] idd=ids.split(",");
		List<Income> list =new ArrayList<Income>();
		for(String id:idd){
			list.add(incomeService.get(id));
		}

		Export e=new Export();
		e.exportincome(response,list);
	}
	/**
	 * 查看，增加，编辑收入表单页面
	 */
	@RequiresPermissions(value={"ap:income:view","ap:income:add","ap:income:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(Income income, Model model) {
		if(income.getIsNewRecord()){
			income.setDocumentStatus("已创建");
			String pro= UserUtils.getUseroffice();
			if(!pro.equals("总部")){
				income.setProjectName(projectService.findUniqueByProperty("name",pro));
				Department d=departmentService.findUniqueByProperty("project",projectService.findUniqueByProperty("name",pro).getId());
				income.setDepartment(d.getName());
			}
			Income i=new Income();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
			String code=UserUtils.getUserAre()+sdf.format(new Date());
			i.setDocumentNumber(code);
			List<Income> list=incomeService.findList(i);
			if(list==null||list.size()<1){
				income.setDocumentNumber(code+"001"+"SR");
			}else{
				if(list.size()/10==0){
					income.setDocumentNumber(code+"00"+(list.size()+1)+"SR");
				}else
				if(list.size()/100==0){
					income.setDocumentNumber(code+"0"+(list.size()+1)+"SR");
				}else{income.setDocumentNumber(code+(list.size()+1)+"SR");}

			}
			Staff staff =new Staff();
			staff.setProjectName(UserUtils.getUseroffice());
			List<Staff> l=staffService.findList(staff);
			for(Staff s:l){
				if(staffService.get(s.getId()).getPosition().getName().contains("财务")){
					income.setResponsiblePerson(s);
				}
			}
		}
		model.addAttribute("income", income);
		return "modules/ap/incomeForm";
	}

	/**
	 * 保存收入
	 */
	@ResponseBody
	@RequiresPermissions(value={"ap:income:add","ap:income:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(Income income, Model model, RedirectAttributes redirectAttributes) throws Exception{
		AjaxJson j = new AjaxJson();
		if (!beanValidator(model, income)){
			j.setSuccess(false);
			j.setMsg("非法参数！");
			return j;
		}
		//新增或编辑表单保存
		incomeService.save(income);//保存
		List<EarningsDetail> list=income.getEarningsDetailList();
		if(list!=null&&list.size()>0) {
			Double d = 0.0;
			for (EarningsDetail e : list) {
				d += Double.parseDouble(e.getTotal());
			}
			income.setMoney(d);
			incomeService.save(income);//保存
		}j.setSuccess(true);
		j.setMsg("保存收入成功");
		return j;
	}
	
	/**
	 * 删除收入
	 */
	@ResponseBody
	@RequiresPermissions("ap:income:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(Income income, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		incomeService.delete(income);
		j.setMsg("删除收入成功");
		return j;
	}

	/**
	 * 删除收入
	 */
	@ResponseBody
	@RequestMapping(value = "bh")
	public AjaxJson bh(Income income, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		income.setDocumentStatus("审核未通过");
		incomeService.save(income);
		j.setMsg("驳回成功");
		return j;
	}

	/**
	 * 批量删除收入
	 */
	@ResponseBody
	@RequiresPermissions("ap:income:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			incomeService.delete(incomeService.get(id));
		}
		j.setMsg("删除收入成功");
		return j;
	}
	
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("ap:income:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public AjaxJson exportFile(Income income, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "收入"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<Income> page = incomeService.findPage(new Page<Income>(request, response, -1), income);
    		new ExportExcel("收入", Income.class).setDataList(page.getList()).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出收入记录失败！失败信息："+e.getMessage());
		}
			return j;
    }
    
    @ResponseBody
    @RequestMapping(value = "detail")
	public Income detail(String id) {
		return incomeService.get(id);
	}
	

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("ap:income:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<Income> list = ei.getDataList(Income.class);
			for (Income income : list){
				try{
					incomeService.save(income);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条收入记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条收入记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入收入失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/ap/income/?repage";
    }
	
	/**
	 * 下载导入收入数据模板
	 */
	@RequiresPermissions("ap:income:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "收入数据导入模板.xlsx";
    		List<Income> list = Lists.newArrayList(); 
    		new ExportExcel("收入数据", Income.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/ap/income/?repage";
    }

	@RequestMapping(value = "updateStatus")
	@ResponseBody
	public String updateStatus( Income income   ,HttpServletResponse response,HttpServletRequest request) {
		 String ids=request.getParameter("ids");
		 if(StringUtils.isNotEmpty(ids)){
		 	String[] str=ids.split(",");
		 	if(str!=null&&str.length>0){
		 		for(String id:str){
		 			if(StringUtils.isNotEmpty(id)){
		 				income=incomeService.get(id);
						String position=UserUtils.getposition();
						if(position.equals("办事处经理")){
							income.setDocumentStatus("经理已审批");
						}
						if(position.contains("总监")){
							income.setDocumentStatus("总监已审批");
						}NumberFormat nf = NumberFormat.getInstance();
						if(position.equals("总经理")){
							income.setDocumentStatus("总经理已审批");

							Yue yue=yueService.findUniqueByProperty("pro",income.getProjectName().getName());
							yue.setXj(nf.format(Double.parseDouble(yue.getXj())+income.getMoney()).replaceAll(",",""));
							yue.setZje(nf.format(Double.parseDouble(yue.getZje())+income.getMoney()).replaceAll(",",""));
							yueService.save(yue);
						}
		 				incomeService.save(income);
					}
				}
			}

		 }
		return "sesst";
	}

}